package com.gavin.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @title 占位符替换
 * @author Yudao 王冬明（woyuwodao@gmail.com）
 * @version 1.0
 * @date 2018/12/2 下午8:43
 * @package com.renrenhui.center.user.rpc.util
 */
public class PlaceholderUtils {
    private static final Logger logger = LoggerFactory.getLogger(PlaceholderUtils.class);
    /**
     * Prefix for system property placeholders: "${"
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";
    /**
     * Suffix for system property placeholders: "}"
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    public static final boolean NULL2STRING=false;//默认是null值

    /**
     * 将字符串text中由openToken和closeToken组成的占位符依次替换为args数组中的值
     * @param openToken
     * @param closeToken
     * @param text
     * @param args
     * @return
     */
    public static String parse(String openToken, String closeToken, String text, Object[] args) {
        if (args == null || args.length <= 0) {
            return text;
        }
        int argsIndex = 0;
        if (text == null || text.isEmpty()) {
            return "";
        }
        char[] src = text.toCharArray();
        int offset = 0;
        // search open token
        int start = text.indexOf(openToken, offset);
        if (start == -1) {
            return text;
        }
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        while (start > -1) {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        offset = end + closeToken.length();
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start); offset = src.length;
                } else {
                    String value=(argsIndex <= args.length - 1) ? (args[argsIndex] == null ? null : args[argsIndex].toString()) : expression.toString();
                    value=(value==null && NULL2STRING)?"":null;

                    builder.append(value);
                    offset = end + closeToken.length();
                    argsIndex++;
                }
            }
            start = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }

    public static String parseMap(String openToken, String closeToken, String text, Map<String,Object> params) {


        if (params == null || params.isEmpty()) {
            return text;
        }
//        int argsIndex = 0;
        if (text == null || text.isEmpty()) {
            return "";
        }
        char[] src = text.toCharArray();
        int offset = 0;
        // search open token
        int start = text.indexOf(openToken, offset);
        if (start == -1) {
            return text;
        }
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        while (start > -1) {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        offset = end + closeToken.length();
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start); offset = src.length;
                } else {
                    builder.append(value(expression,params));
                    offset = end + closeToken.length();
//                    argsIndex++;
                }
            }
            start = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }


    public static String defaultParse(String text, Object... args) {
        return parse(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX, text, args);
    }

    public static String defaultParseMap(String text, Map<String,Object> params) {
        return parseMap(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX, text, params);
    }





    private static String value(StringBuilder expression,Map<String,Object> params){
        String value=null;
        if(params==null || params.size()==0){
            if(NULL2STRING)value="";
        }else{
            String defaultValue=null;
            if(expression.indexOf("|")!=-1){//包含默认值
                String[] temps=expression.toString().split("\\|");
                defaultValue=temps[1];
                expression.setLength(0);
                expression=expression.append(temps[0]);
            }
            value = params.get(expression.toString())==null?defaultValue:String.valueOf(params.get(expression.toString()));

        }

        return value;
    }

    public static void main(String[] args) {
        System.out.println(defaultParse("我的名字是${sss},结果是${dsadsadsa}，可信度是%${dsa}","","雷锋", true));

        String text= "我们都是好孩子,${num|默认值}说是嘛？ 我觉得${people}是傻蛋!";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("num1","惊呆了撒娇了");
        map.put("people","小明");
        System.out.println(defaultParseMap(text,map));
    }
}
